<!-- 角色列表 -->
<template>
   <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card class="box-card">
            <!-- 添加角色按钮 -->
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-button type="primary" @click="showAddRolesDialog">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区 -->
            <el-table
                :data="rolesList"
                border
                stripe
                style="width: 100%">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdtop','bdbottom']" 
                                v-for="(item1) in scope.row.children" 
                                :key="item1.id">
                            <!-- 渲染一级列表 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级列表 -->
                            <el-col :span="19">
                                <!-- 通过for循环 嵌套渲染二级权限 -->
                                <el-row :class="[i2 ===0 ? '' : 'bdtop']" 
                                        v-for="(item2, i2) in item1.children" 
                                        :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 渲染三级列表 -->
                                    <el-col :span="13">
                                        <el-tag :class="[i3 ===0 ? '' : 'bdtop']" 
                                                v-for="(item3, i3) in item2.children" 
                                                :key="item3.id"
                                                type="warning"
                                                closable
                                                @close="removeRightById(scope.row, item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <!-- 渲染三级列表 -->
                            <el-col></el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#" ></el-table-column>
                <el-table-column prop="roleName" label="角色名称" ></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述" ></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showModifyUserDialog(scope.row.id)"></el-button>
                        <!-- 删除 -->
                        <template>
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="confirmDelete(scope.row.id)"></el-button>
                        </template>
                        <!-- 分配角色 -->
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
                
            </el-table>
        </el-card>
        <!-- 添加角色的对话框 -->
        <el-dialog
            title="添加角色"
            :visible.sync="addRolesDialogVisible"
            width="50%">
            <!-- 内容主体区 -->
            <el-form :model="addRuleForm" 
                     :rules="addRules" 
                     label-width="100px">
                <el-form-item label="用户角色" prop="roleName">
                    <el-input v-model="addRuleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRuleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRolesDialogVisible=false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户角色的对话框 -->
        <el-dialog
            title="修改用户角色"
            :visible.sync="modifyUserDialogVisible"
            width="50%">
            <!-- 内容主体区 -->
            <el-form :model="modifyRoleForm" 
                     :rules="modifyRules" 
                     ref="ruleForm" 
                     label-width="100px">
                <el-form-item label="用户角色" prop="roleName">
                    <el-input v-model="modifyRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="modifyRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="modifyUserDialogVisible=false">取 消</el-button>
                <el-button type="primary" @click="modifyRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限的对话框 -->
        <el-dialog
            title="分配权限"
            :visible.sync="setRightDialogVisible"
            width="50%"
            @close="clearDefKeys">
            <!-- 内容主体，树形控件 -->
            <el-tree :data="rightsList" 
                     :props="treeProps"
                     show-checkbox
                     node-key="id"
                     default-expand-all
                     :default-checked-keys="defKeys"
                     ref="treeRef">
            </el-tree>
            <!-- 底部区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible=false">取 消</el-button>
                <el-button type="primary" @click="setRights">确 定</el-button>
            </span>
        </el-dialog>
   </div>
</template>

<script>
    export default {
        name: '',
        created() {
            this.getRolesList()
        },
        data () {
            return {
                // 所有角色的数据
                rolesList: [],
                // 所有权限的数据
                rightsList: [],
                // 树形控件的属性绑定对象
                treeProps: {
                    label: 'authName',
                    children: 'children',
                },
                // 默认选中的权限的id
                defKeys: [],
                // 当前正在分配权限的角色id
                roleId: '',
                // 对话框显示与否
                addRolesDialogVisible: false,
                modifyUserDialogVisible: false,
                setRightDialogVisible: false,
                // 添加角色的表单数据
                addRuleForm: {},
                // 添加角色的表单数据规则
                addRules: {
                    // 用户角色的规则
                    roleName: [
                        {
                            required: true,
                            message: '请输入角色',
                            trigger: 'blur'
                        }
                    ],
                    // 角色描述的规则
                    roleDesc: [
                        {
                            required: false,
                        },
                        {
                            min: 0,
                            max: 20,
                            message: '描述不超过20字',
                            trigger: 'blur'
                        }
                    ]
                },
                // 修改角色的表单数据
                modifyRoleForm: {},
                // 修改角色的表单数据规则
                modifyRules: {
                    // 用户角色的规则
                    roleName: [
                        {
                            required: true,
                            message: '请输入角色',
                            trigger: 'blur'
                        }
                    ],
                    // 角色描述的规则
                    roleDesc: [
                        {
                            required: false,
                        },
                        {
                            min: 0,
                            max: 20,
                            message: '描述不超过20字',
                            trigger: 'blur'
                        }
                    ]
                }
            };
        },
        methods: {
            getRolesList: async function(){
                const {data: res} = await this.$http.get('roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表失败')
                }
                this.rolesList = res.data
                console.log(res);
            },
            // 展示添加用户的对话框
            showAddRolesDialog: function() {
                this.addRolesDialogVisible = true
            },
            // 添加角色
            addRole: async function() {
                const {data:res} = await this.$http.post('roles',this.addRuleForm)
                if (res.meta.status != 201) {
                    return this.$message.error('添加用户失败')
                }
                // 隐藏对话框
                this.addRolesDialogVisible = false
                // 重新获取角色列表
                this.getRolesList()
                this.$message.success('添加成功')
            },
            // 展示修改角色的对话框
            showModifyUserDialog: async function(id) {
                const {data:res} = await this.$http.get('roles/'+ id)
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色失败!')
                }
                this.modifyRoleForm = res.data
                this.modifyUserDialogVisible = true
            },
            // 修改角色
            modifyRoles: async function() {
                const {data:res} = await this.$http.put(`roles/${this.modifyRoleForm.roleId}`,this.modifyRoleForm)
                if (res.meta.status !== 200) {
                    return this.$message.error('修改角色失败')
                }
                this.getRolesList()
                this.modifyUserDialogVisible = false
                this.$message.success('修改成功')
            },
            // 确认删除的弹框
            confirmDelete: async function(id) {
                const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', 
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });      
                // console.log('confirmResult: ',confirmResult);
                // 如果用户确认删除，返回字符串confirm
                if (confirmResult === 'confirm'){
                    const {data:res} = await this.$http.delete('roles/'+id)
                    if (res.meta.status !== 200) {
                        return this.$message.error('删除失败!')
                    }
                    this.getRolesList()
                    this.$message.success('删除成功!')
                }
            },
            // 根据id删除权限
            removeRightById: async function(role,rightId) {
                // 弹框提示是否要删除
                const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });
                if (confirmResult === 'confirm'){
                    const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                    if (res.meta.status !== 200) {
                        return this.$message.error('删除失败')
                    }
                    
                    // 不要刷新权限列表，而是重新渲染权限数据
                    // this.getRolesList()
                    role.children = res.data
                    this.$message.success('删除成功！')
                }
            },
            // 展示分配权限的对话框
            showSetRightDialog: async function(role) {
                // 获取当前正在分配权限的用户的id，供分配权限按钮使用
                this.roleId = role.id
                const {data:res} = await this.$http.get('rights/tree')
                if(res.meta.status !== 200) {
                    return this.$message.error('获取权限失败！')
                }
                // 把获取到的权限数据保存到 data 中
                this.rightsList = res.data 
                // 递归获取三级节点的 id
                this.getLeafKeys(role, this.defKeys)

                this.setRightDialogVisible = true
            },
            // 关闭分配权限的对话框，清空defKeys[]
            clearDefKeys: function() {
                this.defKeys = []
            },
            // 递归获取用户下所有权限
            getLeafKeys: function(node, arr) {
                // 如果是三级属性，就把其id放入数组
                if(!node.children) {
                    return arr.push(node.id)
                }
                // 递归搜索所有非三级属性
                node.children.forEach(item => this.getLeafKeys(item, arr))
            },
            // 点击为角色分配权限
            setRights: async function() {
                // 拿到前端选中的权限的id
                const keys = [...this.$refs.treeRef.getCheckedKeys(), 
                              ...this.$refs.treeRef.getHalfCheckedKeys()]
                const idStr = keys.join(',')
                const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
                if(res.meta.status !== 200) {
                    return this.$message.error('更新失败')
                }
                this.setRightDialogVisible = false
                this.getRolesList()
                this.$message.success('更新成功')
            }
        }
    }
</script>
<style lang='less' scoped>
.el-tag {
    margin: 7px;
}
.bdtop {
    border-top: 1px solid #eee;
}
.bdbottom {
    border-bottom: 1px solid #eee;
}

</style>